package net.lovesrc.allin.jobs.backup;

import com.alibaba.fastjson.JSONObject;
import net.lovesrc.allin.biz.stl.StlJy;
import net.lovesrc.allin.biz.stl.StlService;
import net.lovesrc.allin.biz.user.UserService;
import net.lovesrc.allin.jobs.base.BaseJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;

import java.util.List;
import java.util.concurrent.TimeUnit;

//@Component
@Profile("live")
public class StlAutoNewJyJob extends BaseJob {

    @Autowired
    private StlService stlService;

    @Override
    public void runOnce() {
        if (stlService.isNotJyTime()) {
            return;
        }
        Integer newQty = jdbcTemplate.queryForObject("select count(1) from t_stl_jy where status = 'Waiting_Buyer_Pay' and type = '4NextDaySell'", int.class);
        if (newQty >= 8) {
            return;
        }
        Integer autoNewJyInterval = tryGetProperties(int.class, 50, "STL_Auto_New_Jy_Interval");
        String randMobile = jdbcTemplate.queryForObject("select mobile from t_stl_account where worked = 1 order by rand() limit 1", String.class);
        List<StlJy> buyJyList = stlService.getBuyJyList(randMobile);
        if (buyJyList.isEmpty()) {
            return;
        }
        int maxJyId = buyJyList.stream()
                .mapToInt(r -> r.getJyId())
                .max()
                .getAsInt();
        {
            JSONObject latestSystemJy = queryForRow(jdbcTemplate, "select * from t_stl_jy where type = '4NextDaySell' order by jyId desc limit 1");
            Long latestSystemJyId = latestSystemJy.getLong("jyId");
            if (maxJyId >= latestSystemJyId + autoNewJyInterval) {
                // 自动生成小号交易（大额额度）
                stlService.newSysJy(UserService.SYSTEM);
            }
        }
    }

    @Override
    protected long intervalMilliseconds() {
        return TimeUnit.SECONDS.toMillis(10);
    }

}
